package org.dx.oho.service.impl;

import org.dx.oho.dao.AreaDao;
import org.dx.oho.entity.Area;
import org.dx.oho.service.AreaService;
import org.jetbrains.annotations.NotNull;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * create by duanx 2020/11/19
 *@description： AreaService实现类
 *@classname: AreaServiceImpl
 *@author: duanx
 *@date: 2020/11/19 20:47
 **/
@Service
public class AreaServiceImpl implements AreaService {

    private final AreaDao areaDao;

    private final RedisTemplate<String ,Object> redisTemplate;

    public AreaServiceImpl(AreaDao areaDao, RedisTemplate<String, Object> redisTemplate) {
        this.areaDao = areaDao;
        this.redisTemplate = redisTemplate;
    }

    /**
     * @author: 旭
     * @date: 2020/12/17
     * 所有返回子区划
     * 此方法频繁以父区划ID列为条件查询结果，需要在此列建索引
     * 当然数据量小就无所谓了
     * @param areas 区划表
     */
    private void getChild(@NotNull List<Area> areas, List<Area> child){
        //存放用来递归的条件
        List<Area> areaList = new ArrayList<>();
        for (Area value : areas) {
            //构造一个区划，设置父区划ID
            Area area = new Area();
            area.setParentId(value.getAreaId());
            //查此父ID下的子区划
            List<Area> list = areaDao.queryAreaByRequirement(area);
            //保存到结果里
            child.addAll(list);
            //保存当作下次查询条件
            areaList.addAll(list);
        }
        //更新查询条件
        areas = areaList;
        //如果查询条件集空了就结束,查不到下级子区划了
        if (areaList.size()>0){
            getChild(areas,child);
        }
    }

    /**
     * 获取给定ID的区划的所有子区划
     * @param areaId 区划ID
     * @return 给定ID的区划的所有子区划
     */
    @Override
    public List<Area> getChileAreaList(Integer areaId) {
        Area area  = new Area();
        area.setAreaId(areaId);
        List<Area> areaList  = areaDao.queryAreaByRequirement(area);
        List<Area> child = new ArrayList<>(areaList);
        getChild(areaList,child);
        redisTemplate.opsForList().leftPushAll("areaChildes",child);
        List<Area> areas = (List<Area>) redisTemplate.opsForList().leftPop("areaChildes");
        return child;
    }

    @Override
    public List<Area> getAllAreaList() {
        return areaDao.queryAreaByRequirement(new Area());
    }

}
